<?php

namespace app\worker\controller\kefu;

use Throwable;
use think\facade\Db;
use app\common\controller\Frontend;
use app\admin\library\Auth as AdminAuth;
use app\worker\library\kefu\Auth as KeFuAuth;
use app\common\library\token\TokenExpirationException;

/**
 * 客服系统扩展接口示例
 */
class Examples extends Frontend
{
    protected KeFuAuth  $keFuAuth;
    protected AdminAuth $adminAuth;

    protected array $noNeedLogin = ['goods', 'orders'];

    /**
     * 客服系统配置
     */
    protected array $config;

    /**
     * 初始化（验权、获取配置）
     * @throws Throwable
     */
    public function initialize(): void
    {
        parent::initialize();

        // 客服系统配置初始化
        $configData = Db::name('kefu_config')->select();
        foreach ($configData as $item) {
            $this->config[$item['name']] = $item['value'];
        }

        /**
         * 以下提供了完成各种身份验权的示例，以便开发者根据登录用户获取数据
         * $this->keFuAuth 客服系统的用户验权类实例，管理员和会员最终都能转换为客服系统用户
         * $this->adminAuth 管理员鉴权类实例
         * $this->auth 前台会员鉴权类实例
         */
        $this->keFuAuth  = KeFuAuth::instance();
        $this->adminAuth = AdminAuth::instance();
        $baToken         = get_auth_token(); // 管理token
        $baTouristToken  = get_auth_token(['ba', 'tourist', 'token']); // 游客token

        try {
            // 通过管理员初始化客服用户
            if ($baToken) {
                $this->adminAuth->init($baToken);

                if ($this->adminAuth->isLogin()) {
                    $this->keFuAuth->kfUser('admin', $this->adminAuth->getAdmin()->toArray());
                }
            }

            // 通过会员初始化客服用户 - 由于当前类继承于 Frontend，无需再次通过 token 初始化会员鉴权类
            if (!$this->keFuAuth->isLogin() && $this->auth->isLogin()) {
                $this->keFuAuth->kfUser('user', $this->auth->getUser()->toArray());
            }

            // 客服系统游客
            if (!$this->keFuAuth->isLogin() && $baTouristToken && $this->config['tourist_switch'] == 'yes') {
                $this->keFuAuth->kfUser('tourist', ['token' => $baTouristToken]);
            }
        } catch (TokenExpirationException) {
        }

        if (!$this->keFuAuth->isLogin()) {
            $this->error('无任何可用身份');
        }

        // 至此鉴权初始化完成

        // 若前台管理员已经登录，则 $this->adminAuth 可用，一个管理员（对应 admin 表）登录到了客服系统
        // echo $this->adminAuth->isLogin() ? $this->adminAuth->id : 0;
        // print_r($this->adminAuth->getAdmin());

        // 若前台会员已经登录，则 $this->auth 可用，一个会员（对应 user 表）登录到了客服系统
        // echo $this->auth->isLogin() ? $this->auth->id : 0;
        // print_r($this->auth->getUser());

        // 前台无管理员或会员登录，一个客服系统用户（游客身份，对应 kefu_user 表）登录到了客服系统
        // echo $this->keFuAuth->isLogin() ? $this->keFuAuth->id : 0;
        // print_r($this->keFuAuth->getUser());
    }

    /**
     * 客服系统商品示例接口
     * @throws Throwable
     */
    public function goods(): void
    {
        /**
         * 以下为一个客服系统可用的『商品数据数组』示例
         * 请根据实际情况从已有的商品数据表中读取数据并转换为以下格式，客服系统本身不提供商品数据管理
         */
        $this->success('', [
            [
                'id'       => 1,
                'title'    => '接口演示商品名称-这是一个演示商品，我来自接口/worker/kefu.Examples/goods',
                'logo'     => full_url('/static/kefu/images/affix-1.png'),
                'subtitle' => '接口：/worker/kefu.Examples/goods',
                'price'    => '￥99'
            ],
            [
                'id'       => 2,
                'title'    => '小米9耳机正品type-c适用于8se/10半入耳式mix3 7pro note3/5原装',
                'logo'     => full_url('/static/kefu/images/affix-1.png'),
                'subtitle' => '小米通用',
                'price'    => '￥101'
            ],
            [
                'id'       => 3,
                'title'    => '小米9耳机正品type-c适用于8se/10半入耳式mix3 7pro note3/5原装',
                'logo'     => full_url('/static/kefu/images/affix-1.png'),
                'subtitle' => '小米通用',
                'price'    => '￥102'
            ]
        ]);
    }

    /**
     * 客服系统订单示例接口
     * @throws Throwable
     */
    public function orders(): void
    {
        /**
         * 以下为一个客服系统可用的『订单数据数组』示例
         * 请根据实际情况从已有的订单数据表中读取数据并转换为以下格式，客服系统本身不提供订单数据管理
         */
        $this->success('', [
            [
                'id'       => 1,
                'title'    => '接口演示订单标题-这是一个演示订单，我来自接口/worker/kefu.Examples/orders',
                'logo'     => full_url('/static/kefu/images/affix-1.png'),
                'subtitle' => '接口：/worker/kefu.Examples/orders',
                'amount'   => '￥99',
                'number'   => 1,
            ],
            [
                'id'       => 2,
                'title'    => '小米9耳机正品type-c适用于8se/10半入耳式mix3 7pro note3/5原装',
                'logo'     => full_url('/static/kefu/images/affix-1.png'),
                'subtitle' => '订单属性',
                'amount'   => '￥101',
                'number'   => 2,
            ],
            [
                'id'       => 3,
                'title'    => '小米9正品耳机等3件商品',
                'logo'     => full_url('/static/kefu/images/affix-1.png'),
                'subtitle' => '颜色：红色；礼盒：不要礼盒',
                'amount'   => '￥102',
                'number'   => 3,
            ],
            [
                'id'       => 4,
                'title'    => '小米10正品耳机等3件商品',
                'logo'     => full_url('/static/kefu/images/affix-1.png'),
                'subtitle' => '颜色：红色；礼盒：不要礼盒',
                'amount'   => '￥103',
                'number'   => 4,
            ],
            [
                'id'       => 5,
                'title'    => '小米11正品耳机等3件商品',
                'logo'     => full_url('/static/kefu/images/affix-1.png'),
                'subtitle' => '颜色：红色；礼盒：不要礼盒',
                'amount'   => '￥104',
                'number'   => 5,
            ],
            [
                'id'       => 6,
                'title'    => '小米12正品耳机等3件商品',
                'logo'     => full_url('/static/kefu/images/affix-1.png'),
                'subtitle' => '颜色：红色；礼盒：不要礼盒',
                'amount'   => '￥105',
                'number'   => 6,
            ]
        ]);
    }
}